<?php

namespace App\Http\Controllers\Auth;

use Session;
use App\Models\User as CheckUser;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Http\Request;

class ForgotPasswordController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Password Reset Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling password reset emails and
    | includes a trait which assists in sending these notifications from
    | your application to your users. Feel free to explore this trait.
    |
    */

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    //发送验证码
    public function sendSmsCode(Request $request) {

        if(preg_match("/^1[345678]{1}\d{9}$/",$request->mobile)){
            //判断用户
            $is_user = CheckUser::where('mobile',$request->mobile)->get()->toArray();
            if(!$is_user){
                return ["code"=>10002,"info"=>"用户不存在","data"=>[]];
            }
            //生成验证码存入session
            $code = rand(100000,999999);
            Session::put(['sms' => [
                'mobile'=>$request->mobile,
                'validateCode' => $code
            ]]);
            //发送短信
            $url="http://send.18sms.com/msg/HttpBatchSendSM?account=vd736g&pswd=dTP8X306&mobile=".$request->mobile."&msg=%E6%82%A8%E7%9A%84%E9%AA%8C%E8%AF%81%E7%A0%81%E6%98%AF%EF%BC%9A".$code."&needstatus=true&extno=";
            file_get_contents($url);
            return ["code"=>10000,"info"=>"发送成功","data"=>[]];
        }else{
            return ["code"=>10001,"info"=>"手机号格式错误","data"=>[]];
        }
    }
    //找回密码
    public function findPassword(Request $request)
    {
        //验证
        $sessionMobile = Session::get('sms.mobile');
        $sessionValidateCode = Session::get('sms.validateCode');
        if($request->mobile != $sessionMobile || $request->validateCode != $sessionValidateCode){
            return ["code"=>10001,"info"=>"验证码错误","data"=>[]];
        }
        if($request->password != $request->cpassword){
            return ["code"=>10002,"info"=>"两次输入密码不一致","data"=>[]];
        }
        $is_user = CheckUser::where('mobile',$request->mobile)->get()->toArray();
        if(!$is_user){
            return ["code"=>10003,"info"=>"用户不存在","data"=>[]];
        }

        $updateuser = $this->update($request->all());
        if(!$updateuser){
            return ["code"=>10004,"info"=>"找回失败","data"=>[]];
        }
        return ["code"=>10000,"info"=>"找回成功","data"=>[]];
    }

    //更新密码
    protected function update(array $data)
    {
        return CheckUser::where('mobile',$data['mobile'])->update(['password' => Hash::make($data['password'])]);
    }
    


}
